package com.nail.api.customMake.controller;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.druid.util.StringUtils;
import com.nail.api.customMake.bean.Indent;
import com.nail.api.customMake.service.IInDentService;
import com.nail.api.customMake.service.IPaypalService;
import com.nail.api.user.bean.User;
import com.nail.client.RedisClient;
import com.nail.common.Constant;
import com.nail.controller.BaseController;
import com.nail.enumeration.PaypalPaymentIntent;
import com.nail.enumeration.PaypalPaymentMethod;
import com.nail.utils.IPUtils;
import com.nail.utils.Result4API;
import com.paypal.api.payments.Links;
import com.paypal.api.payments.Payment;
import com.paypal.base.rest.PayPalRESTException;

@Controller
@RequestMapping("/api/pay")
public class PaymentController extends BaseController {
    Logger logger = Logger.getLogger(this.getClass());

    @Autowired
    private IPaypalService paypalService;

    @Autowired
    private IInDentService inDentService;

    @Autowired
    private RedisClient redisClient;

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @PostMapping("/toPay")
    @ResponseBody
    public Result4API toPay(HttpServletRequest request,String orderIds,String token,String payToken){
        String cancelUrl =  "http://www.cicisisi.com/";
        String successUrl = "http://www.cicisisi.com/system/paySuccess?payToken="+payToken+"&orderIds=" + orderIds + "&ltk=" + token;
        Result4API result = new Result4API();
        logger.info(sdf.format(new Date()) +" "+ IPUtils.getRemoteHost(request) + ",用户访问了本接口：toPay" );
        if( StringUtils.isEmpty(orderIds) || StringUtils.isEmpty(token)){
            result.setCode(Constant.API_CODE_501);
            result.setMsg(Constant.API_MSG_501);
            return result;
        }
        User user = (User)redisClient.get(Constant.REDIS_USER_KEY + token);
        BigDecimal TotalPrice = new BigDecimal(0.0D);
        Double dbTotal = 0.0;
        for (String orderId : orderIds.split(",")) {
        	Indent indent = inDentService.getIndentById(user.getId(),orderId);
        	if(indent == null){
        		 logger.info("****** 用户提交空订单 ***********");
        		result.setCode(Constant.API_CODE_2001);
                result.setMsg(Constant.API_MSG_2001);
                return result;
        	}
        	BigDecimal num = new BigDecimal(Double.toString(indent.getNum()));
            BigDecimal price = new BigDecimal(Double.toString(indent.getPrice()));
            //logger.info("*******************"+indent.getNum()+"***********"+indent.getPrice()+"***************"+num.multiply(price));
            TotalPrice = TotalPrice.add(num.multiply(price));
            dbTotal += indent.getTotalPrice();
		} 
        logger.info("*******************用户提交订单  begin **************************");
        logger.info("用户:"+user.getUserName()+",ID:"+user.getId());
        logger.info("orderIds:"+orderIds);
        logger.info("支付金额:"+TotalPrice+",数据库总金额:"+dbTotal);
        logger.info("*******************用户提交订单  end ****************************");
        if(TotalPrice.doubleValue() <= 0){
        	 result.setCode(Constant.API_CODE_2002);
             result.setMsg(Constant.API_MSG_2002);
             return result;
        }
        try {
            Payment payment = paypalService.createPayment(
            		TotalPrice.doubleValue(),
                    "USD",
                    PaypalPaymentMethod.paypal,
                    PaypalPaymentIntent.sale,
                    "payment description",
                    cancelUrl,
                    successUrl);
            for(Links links : payment.getLinks()){
                if(links.getRel().equals("approval_url")){
                    result.setData(links.getHref());
                    result.setCode(Constant.API_CODE_SUCCESS);
                    result.setMsg(Constant.API_MSG_SUCCESS);
                    return result;
                }
            }
            result.setCode(Constant.API_CODE_2001);
            result.setMsg(Constant.API_MSG_2001);
        } catch (PayPalRESTException e) {
            e.printStackTrace();
            logger.error(e.toString());
            result.setCode(Constant.API_CODE_ERROR);
            result.setMsg(Constant.API_MSG_ERROR);
            return result;
        }
        return result;
    }
    
	@GetMapping(value="/getPayTypeByPayToken")
	@ResponseBody
	public Result4API getPayTypeByPayToken(HttpServletRequest request,String payToken){	
		Result4API result = new Result4API();
		logger.info(sdf.format(new Date()) +" "+ IPUtils.getRemoteHost(request) + ",用户访问了本接口：getPayTypeByPayToken" );
		if(StringUtils.isEmpty(payToken)){
			result.setCode(Constant.API_CODE_501);
			result.setMsg(Constant.API_MSG_501);
			return result;
		}
		try {
			result.setCode(Constant.API_CODE_SUCCESS);
			result.setMsg(Constant.API_MSG_SUCCESS);
			result.setData(redisClient.get(payToken));
			logger.info("payToken:"+payToken+",结果:"+redisClient.get(payToken));
			return result;
		} catch (Exception e) {
			logger.error(e.toString());
			e.printStackTrace();
			result.setCode(Constant.API_CODE_ERROR);
			result.setMsg(Constant.API_MSG_ERROR);
			return result;
		}
	}

}
